package mae.app;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Locale;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * Helper class to call the static methods for each individual table.
 * @author DJ
 *
 */
public class CollectionsDatabaseHelper extends SQLiteOpenHelper {

	private static final String DATABASE_PATH = "/data/data/mae.app/";
	private static final String DATABASE_NAME = "collections.db";
	private final Context myContext;
	private static final int DATABASE_VERSION = 1;
	
	public SQLiteDatabase dbSqlite;

	public CollectionsDatabaseHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
		this.myContext = context;
	}

	/**
	 * Calls the static onCreate methods for each individual table
	 */
	@Override
	public void onCreate(SQLiteDatabase database) {

	}

	/**
	 * Calls the static onUpgrade methods for each individual table.
	 */
	@Override
	public void onUpgrade(SQLiteDatabase database, int oldVersion,
			int newVersion) {
		
	}
	
	
	
	private void copyDBFromResource(){
		InputStream inputStream = null;
		OutputStream outStream = null;
		String dbFilePath = DATABASE_PATH + DATABASE_NAME;
		
		try{
			inputStream = myContext.getAssets().open(DATABASE_NAME);
			
			outStream = new FileOutputStream(dbFilePath);
			
			byte[] buffer = new byte[1024];
			int length;
			while ((length = inputStream.read(buffer))>0){
				outStream.write(buffer, 0, length);
			}
			outStream.flush();
			outStream.close();
			inputStream.close();
		}catch(IOException e){
			throw new Error("Problem copying db from resource");
		}
	}
	
	public void createDB(){
		createDatabase();
	}
	
	public void createDatabase() {
boolean dbExist = DBExists();
		
		if(!dbExist){
			this.getWritableDatabase();
			copyDBFromResource();
		}
	}
	public void openDatabase() throws SQLException {
		String myPath = DATABASE_PATH + DATABASE_NAME;
		dbSqlite = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
	}
	
	private boolean DBExists(){
		SQLiteDatabase db = null;
		
		try{
			String databasePath = DATABASE_PATH + DATABASE_NAME;
			db = SQLiteDatabase.openDatabase(databasePath, null, SQLiteDatabase.OPEN_READWRITE);
			db.setLocale(Locale.getDefault());
			db.setLockingEnabled(true);
			db.setVersion(1);
		}catch (SQLException e){
			Log.e("SqlHelper", "database not found");
		}
		if (db!=null){
			db.close();
		}
		return db != null ? true : false; 
	}
	

}
